package pfx;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import org.apache.commons.io.FileUtils;

public class Get_X509_cert {

	/**
	 * 通过 pfx 读取 证书
	 * 1. 以文件的形式转换为 字节数组
	 * 2. 获取 keystore
	 * 3. 使用get  X509Cert
	 * 
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		String pfxPath = "C:\\Users\\Administrator\\Desktop\\ttt\\bankside2501.pfx";
		String password = "123456";
		String subject_DN = "";
		PrivateKey privateKey = null;
		
		X509Certificate x509Certificate =  get_X509_cert(pfxPath, password);
		
		subject_DN = x509Certificate.getSubjectDN().getName();
		System.out.println(subject_DN);

	}
    /**
     * 使用 pfx 获取 证书
     * 
     * @param pfxPath
     * @param password
     * @return
     * @throws Exception
     */
	public static X509Certificate get_X509_cert(String pfxPath,String password) throws Exception{
		
		X509Certificate x509Certificate = null;
		
		File file = new File(pfxPath);
		byte[] byte_pfxPath = FileUtils.readFileToByteArray(file);
		
		KeyStore keyStore = getKeyStore(byte_pfxPath,password);
		
		Enumeration<String> enums = keyStore.aliases();
		String alia = "";
		while(enums.hasMoreElements()){
			alia = enums.nextElement();
			if(keyStore.isKeyEntry(alia)){
				x509Certificate = (X509Certificate) keyStore.getCertificate(alia);
			}	
		}
		return x509Certificate;
	}

	private static KeyStore getKeyStore(byte[] byte_pfxPath, String password) throws Exception {
		
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		keyStore.load(new ByteArrayInputStream(byte_pfxPath), password.toCharArray());
	
		return keyStore;
	}
	
	
}






